package io.renren.modules.live.service.impl;

import io.renren.common.utils.R;
import io.renren.modules.live.dao.FanweAnchorTokenDao;
import io.renren.modules.sys.entity.SysUserTokenEntity;
import io.renren.modules.sys.oauth2.TokenGenerator;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;


import io.renren.modules.live.entity.FanweAnchorTokenEntity;
import io.renren.modules.live.service.FanweAnchorTokenService;


@Service("fanweAnchorTokenService")
public class FanweAnchorTokenServiceImpl extends ServiceImpl<FanweAnchorTokenDao, FanweAnchorTokenEntity> implements FanweAnchorTokenService {
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FanweAnchorTokenEntity> page = this.page(
                new Query<FanweAnchorTokenEntity>().getPage(params),
                new QueryWrapper<FanweAnchorTokenEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public R createToken(Long anchorId) {
        //生成一个token
        String token = "anc"+TokenGenerator.generateValue();
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        //判断是否生成过token
        FanweAnchorTokenEntity anchorTokenEntity = this.getById(anchorId);
        if(anchorTokenEntity == null){
            anchorTokenEntity = new FanweAnchorTokenEntity();
            anchorTokenEntity.setAnchorId(anchorId);
            anchorTokenEntity.setToken(token);
            anchorTokenEntity.setUpdateTime(now);
            anchorTokenEntity.setExpireTime(expireTime);
            //保存token
            this.save(anchorTokenEntity);
        }else{
            anchorTokenEntity.setToken(token);
            anchorTokenEntity.setUpdateTime(now);
            anchorTokenEntity.setExpireTime(expireTime);
            //更新token
            this.updateById(anchorTokenEntity);
        }
        R r = R.ok().put("token", token).put("expire", EXPIRE).put("userId",anchorId);
        return r;
    }

    @Override
    public void logout(Long userId) {
            //生成一个token
            String token = "anc"+TokenGenerator.generateValue();
            //修改token
            FanweAnchorTokenEntity tokenEntity = new FanweAnchorTokenEntity();
            tokenEntity.setAnchorId(userId);
            tokenEntity.setToken(token);
            this.updateById(tokenEntity);

    }

}